package cn.ts.aspect;

import cn.ts.annotation.RateLimit;
import cn.ts.entity.RateLimiterEntity;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;

/**
 * @author: ts
 * @description
 * @create: 2025/3/10 14:52
 */
@Slf4j
public abstract class AbstractRateLimiter {


    public boolean rateLimit(RateLimiterEntity rateLimiterEntity) throws ExecutionException {


        //0. 参数校验
        if (rateLimiterEntity == null){
            return false;
        }

        //1. 黑名单检查
        boolean blacklistCheckResult = blacklistCheck(rateLimiterEntity);
        if (blacklistCheckResult) {
            log.info("限流-黑名单拦截（24h）：{}", rateLimiterEntity.getKey());
            return true;
        }


        //2. 限流
        boolean limitResult = limit(rateLimiterEntity);
        if (limitResult) {
            log.info("限流-超频次拦截：{}", rateLimiterEntity.getKey());
            return true;
        }

        // 放行
        return false;

    }

    protected abstract boolean limit(RateLimiterEntity rateLimiterEntity) throws ExecutionException;

    protected abstract boolean blacklistCheck(RateLimiterEntity rateLimiterEntity) throws ExecutionException;
}
